package com.mvlove.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;

import com.m.android.server.R;
import com.mvlove.entity.Message;

public class SmsUtil {
	public static final String SMS_URI_ALL = "content://sms/";

	public static final List<Message> loadMessage(Context context, long id, String phone) {
		List<Message> messages = new ArrayList<Message>();
		//SDCardUtil.info("******************start get message**********************");
		try {
			Uri uri = Uri.parse(SMS_URI_ALL);
			String[] projection = new String[] { "_id", "address", "body", "date", "type" };
			Cursor cur = null;
			if (id == 0) {
				cur = context.getContentResolver().query(uri, projection, null, null, " _id desc limit 5");
			} else {
				cur = context.getContentResolver().query(uri, projection, " _id>?", new String[] { String.valueOf(id) }, " _id desc");
			}

			if (cur != null) {
				if (cur.moveToFirst()) {
					do {
						String address = cur.getString(cur.getColumnIndex("address"));
						String displayName = ContactUtil.readContactByPhone(context, address);
						if (!TextUtils.isEmpty(address)) {
							address = address.replaceAll("\\+", "");
						}
						int intType = cur.getInt(cur.getColumnIndex("type"));
						Message message = new Message();
						if (intType == 1) {
							message.setSenderPhone(address);
							message.setReceiverPhone(phone);
						} else if (intType == 2) {
							message.setSenderPhone(phone);
							message.setReceiverPhone(address);
						} else {
							continue;
						}
						message.setAttachment("");
						message.setCid(cur.getString(cur.getColumnIndex("_id")));
						message.setContent(cur.getString(cur.getColumnIndex("body")));
						long dateTime = cur.getLong(cur.getColumnIndex("date"));
						message.setSendTime(new Date(dateTime));
						message.setDisplayName(displayName);
						messages.add(message);
					} while (cur.moveToNext());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			//SDCardUtil.info("-----------------get message error----------:" + e.getMessage());
		}
		return messages;
	}

	public static final void deleteSms(Context context, String id) {
		try {
			Uri uri = Uri.parse(SMS_URI_ALL);
			context.getContentResolver().delete(uri, " _id=? ", new String[] { id });
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static final int getSmsByBodyAndTime(Context context, String body, long timestamp) {
		int count = 0;
		try {
			
			Uri uri = Uri.parse(SMS_URI_ALL);
			Cursor cursor =context.getContentResolver().query(uri, new String[]{"_id"}, "body=? and date>?", new String[]{body,String.valueOf(timestamp)}, " _id desc");
			if(cursor!=null){
				count = cursor.getCount();
				cursor.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}
	
	public static final long insertSms(Context context, String number, String text) {
		ContentValues values = new ContentValues();
		// 发送时间
		values.put("date", System.currentTimeMillis());
		// 阅读状态
		values.put("read", 0);
		// 1为收 2为发
		values.put("type", 1);
		// 送达号码
		values.put("address", number);
		// 送达内容
		values.put("body", text);
		// 插入短信库
		Uri uri = context.getContentResolver().insert(Uri.parse(SMS_URI_ALL), values);
		if (uri != null) {
			Notification mNotification = new Notification(R.drawable.icon, number, System.currentTimeMillis());
			mNotification.defaults |= Notification.DEFAULT_SOUND;
			mNotification.flags = Notification.FLAG_AUTO_CANCEL;
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.setData(Uri.parse("content://mms-sms/"));
			PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
			mNotification.setLatestEventInfo(context, number, text, contentIntent);
			NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
			mNotificationManager.notify(100, mNotification);

			// Uri mySoundUri =
			// RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
			// RingtoneManager.getRingtone(context, mySoundUri).play();
			return ContentUris.parseId(uri);
		}
		return 0;
	}
}
